package com.yuntsg.nnsfcp.service.back.Role;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuntsg.nnsfcp.common.exceptions.BaseResponseCode;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.common.utils.VerifyUtil;
import com.yuntsg.nnsfcp.entity.PermissionRespNode;
import com.yuntsg.nnsfcp.entity.RolePermissionOperationReqVO;
import com.yuntsg.nnsfcp.front.entity.TRole;
import com.yuntsg.nnsfcp.front.entity.TUserRole;
import com.yuntsg.nnsfcp.front.mapper.TRoleMapper;
import com.yuntsg.nnsfcp.front.mapper.TUserRoleMapper;
import com.yuntsg.nnsfcp.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 葛成瑞
 * @crete 2021/1/22
 */
@Service
@Slf4j
public class RoleService {

    @Resource
    TRoleMapper tRoleMapper;

    @Resource
    RolePermissionService rolePermissionService;


    @Resource
    TUserRoleMapper tUserRoleMapper;


    @Resource
    CommonService commonService;


    //    /**
//     * 获取角色名
//     *
//     * @param userId 用户id
//     * @return
//     */
//    public String getRoleNames(Long userId) {
//        SysUser sysUser = sysUserService.getById(userId);
//        if (null == sysUser ) {
//            return null;
//        }
//        return Optional.ofNullable(this.getById(sysUser.getRoleId())).orElse(new Role().setName("未指定角色")).getName();
//    }
    @Transactional
    public TRole addRole(TRole vo) {
        vo.setGenTime(LocalDateTime.now());
        int insert = tRoleMapper.insert(vo);
        if (insert != 1) {
            CheckUtil.check(false, BaseResponseCode.OPERATION_ERRO.getMsg());
        }
        if (null != vo.getPermissions() && !vo.getPermissions().isEmpty()) {
            RolePermissionOperationReqVO reqVO = new RolePermissionOperationReqVO();
            reqVO.setRoleId(vo.getId());
            reqVO.setPermissionIds(vo.getPermissions());
            rolePermissionService.addRolePermission(reqVO);
        }
        return vo;
    }

    @Transactional
    public void updateRole(TRole vo) {
        TRole Role = tRoleMapper.selectById(vo.getId());
        if (null == Role) {
            log.error("传入 的 id:{}不合法", vo.getId());
            VerifyUtil.verify(true, BaseResponseCode.DATA_ERROR.getMsg());
        }
        int i = tRoleMapper.updateById(vo);
        if (i != 1) {
            VerifyUtil.verify(true, BaseResponseCode.OPERATION_ERRO.getMsg());
        }
        rolePermissionService.removeByRoleId(Role.getId());
        if (!CollectionUtils.isEmpty(vo.getPermissions())) {
            RolePermissionOperationReqVO reqVO = new RolePermissionOperationReqVO();
            reqVO.setRoleId(Role.getId());
            reqVO.setPermissionIds(vo.getPermissions());
            rolePermissionService.addRolePermission(reqVO);
            //刷新权限
//            httpSessionService.refreshRolePermission(Role.getId());
        }
    }

    public TRole detailInfo(Integer id) {
        TRole Role = tRoleMapper.selectById(id);
        if (Role == null) {
            log.error("传入 的 id:{}不合法", id);
            VerifyUtil.verify(true, BaseResponseCode.DATA_ERROR.getMsg());
        }
        List<PermissionRespNode> permissionRespNodes = commonService.selectAllByTree();
        Set<Integer> checkList = new HashSet<>(rolePermissionService.getPermissionIdsByRoleId(Role.getId()));
        setheckced(permissionRespNodes, checkList);
        Role.setPermissionRespNodes(permissionRespNodes);
        return Role;
    }


    private void setheckced(List<PermissionRespNode> list, Set<Integer> checkList) {
        for (PermissionRespNode node : list) {
            if (checkList.contains(node.getId()) && (node.getChildren() == null || node.getChildren().isEmpty())) {
                node.setChecked(true);
            }
            setheckced((List<PermissionRespNode>) node.getChildren(), checkList);
        }
    }


    @Transactional
    public void deletedRole(Integer id) {
        VerifyUtil.verify(tUserRoleMapper.selectList(new LambdaQueryWrapper<TUserRole>().eq(TUserRole::getRoleId, id)).size() > 0, "当前角色下存在用户，请清理后再删除！");
        int i = tRoleMapper.deleteById(id);
        int b = rolePermissionService.removeByRoleId(id);
        //刷新权限
//        httpSessionService.refreshRolePermission(id);
    }


    public IPage pageInfo(TRole vo) {
        Page page = new Page(vo.getPage(), vo.getLimit());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(vo.getName())) {
            queryWrapper.like("name", vo.getName());
        }
        if (!StringUtils.isEmpty(vo.getStatus())) {
            queryWrapper.eq("status", vo.getStatus());
        }
        queryWrapper.orderByDesc("gen_time");
        return tRoleMapper.selectPage(page, queryWrapper);
    }


    public List<TRole> selectAllRoles() {
        return tRoleMapper.selectList(new QueryWrapper<TRole>().ne("id", 3));
    }
}
